﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using CruxCRUDBuilderHelper.DTOs;
using CruxCRUDBuilderHelper.Utility;


namespace CruxCRUDBuilderHelper
{
    public class GenerateCode
    {
        public void GetTables(string fileName)
        {
            AssemblyInfo.TableNames = new Dictionary<string, string>();
            AssemblyInfo.Attributes = new Dictionary<string, string>();
            Assembly assembly = Assembly.LoadFrom(fileName);
            Type[] alltypes = assembly.GetTypes();
            PropertyInfo[] info;
            foreach (Type temp in alltypes)
            {
                if (temp.Name.Contains("DataContext"))
                    CodeAttribute.DataContextName = temp.Name;
                object[] dbName = temp.GetCustomAttributes(typeof(System.Data.Linq.Mapping.DatabaseAttribute), false);
                if (dbName.Length == 1)
                {
                    AssemblyInfo.SelectedDatabase = ((System.Data.Linq.Mapping.DatabaseAttribute)dbName[0]).Name;

                }
            }
            foreach (Type temp in alltypes)
            {
                object[] attributes = temp.GetCustomAttributes(typeof(System.Data.Linq.Mapping.TableAttribute), false);
                if (attributes.Length == 1)
                {
                    AssemblyInfo.TableNames.Add(((System.Data.Linq.Mapping.TableAttribute)attributes[0]).Name.Replace("dbo.", ""), temp.Name);

                }
            }
            foreach (Type temp in alltypes)
            {
                PropertyInfo[] propertyInfo = temp.GetProperties();
                foreach (PropertyInfo pInfo in propertyInfo)
                {
                    if (pInfo.PropertyType.FullName.Contains("System.Data.Linq.Table"))
                    {
                        if (!AssemblyInfo.Attributes.ContainsKey(pInfo.PropertyType.FullName))
                        {
                            string[] dbmlName = pInfo.PropertyType.FullName.Split(',')[0].Split('.');
                            AssemblyInfo.Attributes.Add(dbmlName[dbmlName.Length - 1],
                                                        pInfo.Name);
                        }
                    }
                }
            }
        }

        public void GetSelectedTable(List<TableInfo> tables, string viewNamespace, string queryClassName, string projectLoc, string namespaceQuery, string namespaceFacade, string namespaceDTO, string namespaceConverter, string namespaceController, string classConverterName, string BONamespace, string section, string dataContextVariable)
        {
            AssemblyInfo.SelectedTables = tables;
            CodeAttribute.BusinessObjectNameSpace = BONamespace;
            CodeAttribute.ClassConverterClassName = classConverterName;
            CodeAttribute.ControllerNamespace = namespaceController;
            CodeAttribute.ConvertorNamespace = namespaceConverter;
            CodeAttribute.DTONamespace = namespaceDTO;
            CodeAttribute.FacadeNamespace = namespaceFacade;
            CodeAttribute.ProjectLoc = projectLoc;
            CodeAttribute.QueryClassName = queryClassName;
            CodeAttribute.QueryNamespace = namespaceQuery;
            CodeAttribute.ViewNamespace = viewNamespace;
            CodeAttribute.PageSection = section;
            CodeAttribute.DataContextVariable = dataContextVariable;
        }

        public void GenerateDTO()
        {
            foreach (TableInfo table in AssemblyInfo.SelectedTables)
            {
                List<FieldStructure> fields = new List<FieldStructure>();
                fields = TableAttributes.GetTableAttributes(table.DbTableName);
                CreateDTO(fields, table.DbmlTableName);
                foreach (FieldStructure row in fields)
                {
                    if ((row.ConstraintType == "F") && (!string.IsNullOrEmpty(row.RefColumnNameField.Trim())))
                    {
                        List<FieldStructure> refField = new List<FieldStructure>();
                        string refTableName = row.RefTableName;
                        refField = TableAttributes.GetTableAttributes(refTableName);
                        CreateDTO(refField, GetRefTableDBMLName(row.RefTableName));
                    }
                }
            }
        }

        private string GetRefTableDBMLName(string refTableName)
        {
            return AssemblyInfo.TableNames.Where(a => a.Key == refTableName).FirstOrDefault().Value;
        }

        private void CreateDTO(List<FieldStructure> fields, string tableName)
        {
            string templateText = string.Empty;
            string fileContent = string.Empty;
            StreamReader streamReader = new StreamReader(@"DTO.txt");
            templateText = streamReader.ReadToEnd();
            streamReader.Close();

            templateText = templateText.Replace("#nameSpace#", CodeAttribute.DTONamespace);
            templateText = templateText.Replace("#classPrefix#", tableName);
            string strIteratorOutput = "";
            string dataType;

            foreach (FieldStructure row in fields)
            {
                string strIterator = new UtilityMethod().GetIteratorPattern(templateText);
                dataType = row.DataType.ToString().Split(' ')[0];

                string isNullable = ((row.NullAble && TableAttributes.GetDataType(dataType).ToLower() != "string") ? "?" : "");

                strIterator = strIterator.Replace("#fldDataType#", TableAttributes.GetDataType(dataType));
                strIterator = strIterator.Replace("#fldName#", isNullable + row.Field);

                strIteratorOutput = strIteratorOutput + Environment.NewLine + strIterator;
            }

            fileContent = templateText.Replace("~[" + new UtilityMethod().GetIteratorPattern(templateText) + "]~", strIteratorOutput);
            File.WriteAllText(CodeAttribute.ProjectLoc + "\\" + tableName + "Information.cs", fileContent);
        }

        public void GenerateView()
        {
            foreach (TableInfo table in AssemblyInfo.SelectedTables)
            {
                List<FieldStructure> fields = new List<FieldStructure>();
                fields = TableAttributes.GetTableAttributes(table.DbTableName);
                CreateView(fields, table.DbmlTableName);
            }
        }

        private void CreateView(List<FieldStructure> fields, string tableName)
        {
            string templateText = string.Empty;
            StreamReader streamReader = new StreamReader(@"view.txt");
            templateText = streamReader.ReadToEnd();
            streamReader.Close();
            templateText = templateText.Replace("#nameSpace#", CodeAttribute.ViewNamespace);
            templateText = templateText.Replace("#viewName#", tableName);
            templateText = templateText.Replace("#DTO#", tableName + "Information");
            templateText = templateText.Replace("#allEntity#", "All" + tableName);
            templateText = templateText.Replace("#currentEntity#", "Current" + tableName);
            templateText = templateText.Replace("#dtoNameSpace#", CodeAttribute.DTONamespace);

            StringBuilder fkInfo = new StringBuilder(String.Empty);

            foreach (FieldStructure row in fields)
            {
                if ((row.ConstraintType == "F") && (!string.IsNullOrEmpty(row.RefColumnNameField.Trim())))
                {
                    string strIterator = new UtilityMethod().GetIteratorPatternForDependentField(templateText);
                    strIterator = strIterator.Replace("#dependentDTO#", GetRefTableDBMLName(row.RefTableName) + "Information");
                    strIterator = strIterator.Replace("#dependentallEntity#", "All" + row.RefTableName);
                    fkInfo = fkInfo.Append(Environment.NewLine + strIterator);
                }
            }
            templateText = templateText.Replace("$[" + new UtilityMethod().GetIteratorPatternForDependentField(templateText) + "]$", fkInfo.ToString());
            File.WriteAllText(CodeAttribute.ProjectLoc + "\\I" + tableName + ".cs", templateText);
        }

        public void GenerateClassConverter()
        {
            foreach (TableInfo table in AssemblyInfo.SelectedTables)
            {
                List<FieldStructure> fields = new List<FieldStructure>();
                fields = TableAttributes.GetTableAttributes(table.DbTableName);
                CreateConverter(fields, table.DbmlTableName);
                foreach (FieldStructure row in fields)
                {
                    if ((row.ConstraintType == "F") && (!string.IsNullOrEmpty(row.RefColumnNameField.Trim())))
                    {
                        List<FieldStructure> refField = new List<FieldStructure>();
                        string refTableName = row.RefTableName;
                        refField = TableAttributes.GetTableAttributes(refTableName);
                        CreateConverter(refField, GetRefTableDBMLName(refTableName));
                    }
                }
            }
        }

        private void CreateConverter(List<FieldStructure> fields, string tableName)
        {
            string templateText = string.Empty;
            StreamReader streamReader = new StreamReader(@"ClassConverter.txt");
            templateText = streamReader.ReadToEnd();
            streamReader.Close();
            templateText = templateText.Replace("#businessObjectNameSpace#", CodeAttribute.BusinessObjectNameSpace);
            templateText = templateText.Replace("#converterNameSpace#", CodeAttribute.ConvertorNamespace);
            templateText = templateText.Replace("#convertorClass#", CodeAttribute.ClassConverterClassName);
            templateText = templateText.Replace("#dtoNameSpace#", CodeAttribute.DTONamespace);
            StringBuilder strIteratorOutput = new StringBuilder(String.Empty);

            foreach (FieldStructure row in fields)
            {
                string strIterator = new UtilityMethod().GetIteratorPattern(templateText);

                strIterator = strIterator.Replace("#dtoDataMember#", row.Field);
                strIterator = strIterator.Replace("#dbmlDataMember#", row.Field);

                strIterator = strIterator.Replace("#dbmlType#", tableName);

                strIteratorOutput = strIteratorOutput.Append(Environment.NewLine + strIterator + " ,");
            }
            templateText = templateText.Replace("~[" + new UtilityMethod().GetIteratorPattern(templateText) + "]~", strIteratorOutput.ToString().Substring(0, strIteratorOutput.ToString().Length - 2));

            strIteratorOutput = new StringBuilder(String.Empty);

            foreach (FieldStructure row in fields)
            {
                string strIterator = new UtilityMethod().GetIteratorPattern2(templateText);

                strIterator = strIterator.Replace("#dtoDataMember#", row.Field);
                strIterator = strIterator.Replace("#dbmlDataMember#", row.Field);
                strIterator = strIterator.Replace("#dtoType#", tableName + "Information");
                strIterator = strIterator.Replace("#dbmlType#", tableName);

                strIteratorOutput = strIteratorOutput.Append(Environment.NewLine + strIterator + " ;");
            }

            templateText = templateText.Replace("~[[" + new UtilityMethod().GetIteratorPattern2(templateText) + "]]~", strIteratorOutput.ToString());
            templateText = templateText.Replace("#dtoType#", tableName + "Information");
            templateText = templateText.Replace("#dbmlType#", tableName);
            File.WriteAllText(CodeAttribute.ProjectLoc + "\\" + CodeAttribute.ClassConverterClassName + "_" + tableName + ".cs", templateText);
        }

        public void GenerateQuery()
        {
            foreach (TableInfo table in AssemblyInfo.SelectedTables)
            {
                List<FieldStructure> fields = new List<FieldStructure>();
                fields = TableAttributes.GetTableAttributes(table.DbTableName);
                CreateQuery(fields, table.DbmlTableName);
            }
        }

        private void CreateQuery(List<FieldStructure> fields, string tableName)
        {
            string templateText = string.Empty;
            StreamReader streamReader = new StreamReader(@"queries.txt");
            templateText = streamReader.ReadToEnd();
            streamReader.Close();
            templateText = templateText.Replace("#BONameSpace#", CodeAttribute.BusinessObjectNameSpace);
            templateText = templateText.Replace("#queryNameSpace#", CodeAttribute.QueryNamespace);
            templateText = templateText.Replace("#className#", CodeAttribute.QueryClassName);
            templateText = templateText.Replace("#entity#", tableName);
            templateText = templateText.Replace("#dbtype#", GetDBType(tableName));
            templateText = templateText.Replace("#datacontext#", CodeAttribute.DataContextVariable);
            string primaryKey = fields.Where(a => a.ConstraintType == "P").Single().Field;
            string primaryKeyDataType =
                TableAttributes.GetDataType(fields.Where(a => a.ConstraintType == "P").Single().DataType);
            templateText = templateText.Replace("#pkField#", primaryKey);
            templateText = templateText.Replace("#pkFieldDataType#", primaryKeyDataType);
            templateText = templateText.Replace("$[" + new UtilityMethod().GetIteratorPatternForDependentField(templateText) + "]$", string.Empty);
            File.WriteAllText(CodeAttribute.ProjectLoc + "\\" + CodeAttribute.QueryClassName + "_" + tableName + ".cs", templateText);

            foreach (FieldStructure row in fields)
            {
                if ((row.ConstraintType == "F") && (!string.IsNullOrEmpty(row.RefColumnNameField.Trim())))
                    GenerateQueriesForDependentTable(row);
            }
        }

        private void GenerateQueriesForDependentTable(FieldStructure row)
        {
            string templateText = string.Empty;
            StreamReader streamReader = new StreamReader(@"queries.txt");
            templateText = streamReader.ReadToEnd();
            streamReader.Close();
            templateText = GetContentToWrite(templateText);
            templateText = templateText.Replace("#BONameSpace#", CodeAttribute.BusinessObjectNameSpace);
            templateText = templateText.Replace("#queryNameSpace#", CodeAttribute.QueryNamespace);
            templateText = templateText.Replace("#className#", CodeAttribute.QueryClassName);
            templateText = templateText.Replace("#datacontext#", CodeAttribute.DataContextVariable);
            templateText = templateText.Replace("#dependentEntity#", GetRefTableDBMLName(row.RefTableName));
            templateText = templateText.Replace("#dependentDbtype#", row.RefTableName);
            File.WriteAllText(CodeAttribute.ProjectLoc + "\\" + CodeAttribute.QueryClassName + "_" + GetRefTableDBMLName(row.RefTableName) + ".cs", templateText);
        }

        private string GetContentToWrite(string templateText)
        {
            int endPos = templateText.IndexOf('{');
            endPos = templateText.IndexOf('{', endPos + 1);
            string content = templateText.Substring(0, endPos + 1);
            content = content + Environment.NewLine;
            string strIterator = new UtilityMethod().GetIteratorPatternForDependentField(templateText);
            strIterator = strIterator + Environment.NewLine + "}" + Environment.NewLine + "}";
            content = content + strIterator;
            return content;
        }

        private string GetDBType(string tableName)
        {
            return AssemblyInfo.Attributes.Where(a => a.Key == tableName).FirstOrDefault().Value;
        }

        public void GenerateFacade()
        {
            foreach (TableInfo table in AssemblyInfo.SelectedTables)
            {
                List<FieldStructure> fields = new List<FieldStructure>();
                fields = TableAttributes.GetTableAttributes(table.DbTableName);
                CreateFacade(fields, table.DbmlTableName);
            }
        }

        private void CreateFacade(List<FieldStructure> fields, string tableName)
        {
            string templateText = string.Empty;
            StreamReader streamReader = new StreamReader(@"facade.txt");
            templateText = streamReader.ReadToEnd();
            streamReader.Close();
            templateText = templateText.Replace("#queryNameSpace#", CodeAttribute.QueryNamespace);
            templateText = templateText.Replace("#BONameSpace#", CodeAttribute.BusinessObjectNameSpace);
            templateText = templateText.Replace("#converterNameSpace#", CodeAttribute.ConvertorNamespace);
            templateText = templateText.Replace("#dtoNameSpace#", CodeAttribute.DTONamespace);
            templateText = templateText.Replace("#facadeNameSpace#", CodeAttribute.FacadeNamespace);
            templateText = templateText.Replace("#className#", tableName + "Facade");
            templateText = templateText.Replace("#dtoType#", tableName + "Information");
            templateText = templateText.Replace("#entityName#", tableName);
            templateText = templateText.Replace("#convertName#", CodeAttribute.ClassConverterClassName);
            templateText = templateText.Replace("#dbmlType#", tableName);
            templateText = templateText.Replace("#QueryName#", CodeAttribute.QueryClassName);
            string primaryKey = fields.Where(a => a.ConstraintType == "P").Single().Field;
            string primaryKeyDataType =
                 TableAttributes.GetDataType(fields.Where(a => a.ConstraintType == "P").Single().DataType);
            templateText = templateText.Replace("#pkFieldDataType#", primaryKeyDataType);
            templateText = templateText.Replace("#pkField#", primaryKey);
            string code = string.Empty;
            if (primaryKeyDataType.ToLower() == "string")
                code = code + "if (string.IsNullOrEmpty(" + primaryKey + "))";
            else
                code = code + "if (" + primaryKey + " == 0)";
            code = code + "return new " + tableName + "Information();";
            code = code + Environment.NewLine;
            templateText = templateText.Replace("#nullLogic#", code);

            StringBuilder fkInfo = new StringBuilder(String.Empty);

            foreach (FieldStructure row in fields)
            {
                if ((row.ConstraintType == "F") && (!string.IsNullOrEmpty(row.RefColumnNameField.Trim())))
                {
                    string strIterator = new UtilityMethod().GetIteratorPatternForDependentField(templateText);
                    strIterator = strIterator.Replace("#dependentDtoType#", GetRefTableDBMLName(row.RefTableName) + "Information");
                    strIterator = strIterator.Replace("#dependentQueryName#", CodeAttribute.QueryClassName);
                    strIterator = strIterator.Replace("#dependentEntityName#", GetRefTableDBMLName(row.RefTableName));
                    strIterator = strIterator.Replace("#dependentconvertName#", CodeAttribute.ClassConverterClassName);
                    fkInfo = fkInfo.Append(Environment.NewLine + strIterator);
                }
            }
            templateText = templateText.Replace("$[" + new UtilityMethod().GetIteratorPatternForDependentField(templateText) + "]$", fkInfo.ToString());
            File.WriteAllText(CodeAttribute.ProjectLoc + "\\" + tableName + "Facade.cs", templateText);
        }

        public void GenerateController()
        {
            foreach (TableInfo table in AssemblyInfo.SelectedTables)
            {
                List<FieldStructure> fields = new List<FieldStructure>();
                fields = TableAttributes.GetTableAttributes(table.DbTableName);
                CreateController(fields, table.DbmlTableName);
            }
        }

        private void CreateController(List<FieldStructure> fields, string tableName)
        {
            string templateText = string.Empty;
            StreamReader streamReader = new StreamReader(@"controller.txt");
            templateText = streamReader.ReadToEnd();
            streamReader.Close();
            templateText = templateText.Replace("#facadeNameSpace#", CodeAttribute.FacadeNamespace);
            templateText = templateText.Replace("#viewNameSpace#", CodeAttribute.ViewNamespace);
            templateText = templateText.Replace("#dtoNameSpace#", CodeAttribute.DTONamespace);
            templateText = templateText.Replace("#controllerNamespace#", CodeAttribute.ControllerNamespace);
            templateText = templateText.Replace("#controllerName#", tableName + "Controller");
            templateText = templateText.Replace("#interface#", "I" + tableName);
            templateText = templateText.Replace("#facadeName#", tableName + "Facade");
            templateText = templateText.Replace("#entityName#", tableName);
            string primaryKey = fields.Where(a => a.ConstraintType == "P").Single().Field;
            string primaryKeyDataType =
                 TableAttributes.GetDataType(fields.Where(a => a.ConstraintType == "P").Single().DataType);
            templateText = templateText.Replace("#pkFieldDataType#", primaryKeyDataType);
            templateText = templateText.Replace("#pkField#", primaryKey);

            StringBuilder fkInfo = new StringBuilder(String.Empty);

            foreach (FieldStructure row in fields)
            {
                if ((row.ConstraintType == "F") && (!string.IsNullOrEmpty(row.RefColumnNameField.Trim())))
                {
                    string strIterator = new UtilityMethod().GetIteratorPatternForDependentField(templateText);
                    strIterator = strIterator.Replace("#dependentallEntity#", "All" + row.RefTableName);
                    strIterator = strIterator.Replace("#dependentEntityName#", GetRefTableDBMLName(row.RefTableName));
                    fkInfo = fkInfo.Append(Environment.NewLine + strIterator);
                }
            }
            templateText = templateText.Replace("$[" + new UtilityMethod().GetIteratorPatternForDependentField(templateText) + "]$", fkInfo.ToString());
            File.WriteAllText(CodeAttribute.ProjectLoc + "\\" + tableName + "Controller.cs", templateText);
        }

        public void GenerateUI()
        {
            foreach (TableInfo table in AssemblyInfo.SelectedTables)
            {
                List<FieldStructure> fields = new List<FieldStructure>();
                fields = TableAttributes.GetTableAttributes(table.DbTableName);
                CreateUI(fields, table.DbmlTableName, table.DbmlTableName);
                CreateCodeBehind(fields, table.DbmlTableName);
                CreateConfig(table.DbmlTableName);
            }
        }

        private void CreateConfig(string tableName)
        {
            string templateText = string.Empty;
            StreamReader streamReader = new StreamReader(@"config.txt");
            templateText = streamReader.ReadToEnd();
            streamReader.Close();
            templateText = templateText.Replace("#section#", CodeAttribute.PageSection);
            templateText = templateText.Replace("#viewName#", tableName);
            File.AppendAllText(CodeAttribute.ProjectLoc + "\\crux.config", templateText);
        }

        private void CreateCodeBehind(List<FieldStructure> fields, string tableName)
        {
            string codeBehindContent = string.Empty;
            StreamReader streamReader = new StreamReader(@"codeBehind.txt");
            codeBehindContent = streamReader.ReadToEnd();
            streamReader.Close();
            string strIterator = String.Empty;
            StringBuilder strIteratorOutput = new StringBuilder(String.Empty);

            codeBehindContent = codeBehindContent.Replace("#interface#", "I" + tableName);
            codeBehindContent = codeBehindContent.Replace("#dtoType#", tableName + "Information");
            codeBehindContent = codeBehindContent.Replace("#dbmlName#", tableName);
            codeBehindContent = codeBehindContent.Replace("#controllerNameSpace#", CodeAttribute.ControllerNamespace);
            codeBehindContent = codeBehindContent.Replace("#dtoNameSpace#", CodeAttribute.DTONamespace);
            codeBehindContent = codeBehindContent.Replace("#viewNameSpace#", CodeAttribute.ViewNamespace);
            codeBehindContent = codeBehindContent.Replace("#controllerClass#", tableName + "Controller");
            codeBehindContent = codeBehindContent.Replace("#gridName#", "grd" + tableName);

            codeBehindContent = codeBehindContent.Replace("#pageName#", tableName);

            codeBehindContent = codeBehindContent.Replace("#allEntity#", "All" + tableName);
            codeBehindContent = codeBehindContent.Replace("#currentEntity#", "Current" + tableName);
            string primaryKeyDataType =
                 TableAttributes.GetDataType(fields.Where(a => a.ConstraintType == "P").Single().DataType);
            switch (primaryKeyDataType)
            {
                case "int":
                    codeBehindContent = codeBehindContent.Replace("#pkFieldDataType#", "int.Parse");
                    break;
                case "long":
                    codeBehindContent = codeBehindContent.Replace("#pkFieldDataType#", "long.Parse");
                    break;
                case "decimal":
                    codeBehindContent = codeBehindContent.Replace("#pkFieldDataType#", "decimal.Parse");
                    break;
                case "string":
                    codeBehindContent = codeBehindContent.Replace("#pkFieldDataType#", "Convert.ToString");
                    break;
            }

            foreach (FieldStructure row in fields)
            {
                strIterator = new UtilityMethod().GetIteratorPattern(codeBehindContent);

                strIterator = strIterator.Replace("#dtoDataMember#", row.Field);

                switch (TableAttributes.GetDataType(row.DataType))
                {
                    case "int":
                        if (row.ConstraintType == "F")
                            strIterator = strIterator.Replace("#controlValue#", "int.Parse(ddl" + row.Field + ".SelectedValue)");
                        else
                            strIterator = row.ConstraintType == "P" ? strIterator.Replace("#controlValue#", "int.Parse(lbl" + row.Field + "Value.Text)") : strIterator.Replace("#controlValue#", "int.Parse(txt" + row.Field + ".Text)");
                        break;
                    case "long":
                        if (row.ConstraintType == "F")
                            strIterator = strIterator.Replace("#controlValue#", "long.Parse(ddl" + row.Field + ".SelectedValue)");
                        else
                            strIterator = row.ConstraintType == "P" ? strIterator.Replace("#controlValue#", "long.Parse(lbl" + row.Field + "Value.Text)") : strIterator.Replace("#controlValue#", "long.Parse(txt" + row.Field + ".Text)");
                        break;
                    case "decimal":
                        if (row.ConstraintType == "F")
                            strIterator = strIterator.Replace("#controlValue#", "decimal.Parse(ddl" + row.Field + ".SelectedValue)");
                        else
                            strIterator = row.ConstraintType == "P" ? strIterator.Replace("#controlValue#", "decimal.Parse(lbl" + row.Field + "Value.Text)") : strIterator.Replace("#controlValue#", "decimal.Parse(txt" + row.Field + ".Text)");
                        break;

                    case "bool":
                        strIterator = strIterator.Replace("#controlValue#", "chk" + row.Field + ".Checked");
                        break;
                    case "DateTime":
                        strIterator = strIterator.Replace("#controlValue#", "Convert.ToDateTime(txt" + row.Field + ".Text)");
                        break;
                    default:
                        if (row.ConstraintType == "F")
                            strIterator = strIterator.Replace("#controlValue#", "decimal.Parse(ddl" + row.Field + ".SelectedValue)");
                        else
                            strIterator = row.ConstraintType == "P" ? strIterator.Replace("#controlValue#", "lbl" + row.Field + "Value.Text") : strIterator.Replace("#controlValue#", "txt" + row.Field + ".Text");
                        break;


                }
                strIteratorOutput.Append(Environment.NewLine + strIterator);
            }



            codeBehindContent = codeBehindContent.Replace("~[" + new UtilityMethod().GetIteratorPattern(codeBehindContent) + "]~", strIteratorOutput.ToString().Substring(0, strIteratorOutput.ToString().Length - 1));

            strIteratorOutput = new StringBuilder(String.Empty);
            foreach (FieldStructure row in fields)
            {
                strIterator = new UtilityMethod().GetIteratorPattern2(codeBehindContent);

                if (row.ConstraintType == "F")
                {
                    strIterator = strIterator.Replace("#controlValue#", "ddl" + row.Field + ".SelectedIndex");
                    string ddlDef = "ddl" + row.Field + ".Items.IndexOf(ddl" + row.Field + ".Items.FindByValue(value." + row.Field + ".ToString()))";
                    strIterator = strIterator.Replace("#valueDataMember#", ddlDef);
                }
                else
                {

                    if (TableAttributes.GetDataType(row.DataType) == "bool")
                    {
                        strIterator = strIterator.Replace("#controlValue#", "chk" + row.Field + ".Checked");
                        strIterator = strIterator.Replace("#valueDataMember#", "value." + row.Field);
                    }
                    else
                    {
                        if (TableAttributes.GetDataType(row.DataType).ToLower() == "datetime")
                            strIterator = strIterator.Replace("#valueDataMember#", "value." + row.Field + ".ToShortDateString()");
                        else if (TableAttributes.GetDataType(row.DataType) != "string")
                            strIterator = strIterator.Replace("#valueDataMember#", "value." + row.Field + ".ToString()");
                        else
                            strIterator = strIterator.Replace("#valueDataMember#", "value." + row.Field);



                        if (row.ConstraintType == "P")
                            strIterator = strIterator.Replace("#controlValue#", "lbl" + row.Field + "Value.Text");
                        else
                            strIterator = strIterator.Replace("#controlValue#", "txt" + row.Field + ".Text");
                    }
                }
                strIteratorOutput.Append(Environment.NewLine + strIterator);

            }


            codeBehindContent = codeBehindContent.Replace("~[[" + new UtilityMethod().GetIteratorPattern2(codeBehindContent) + "]]~", strIteratorOutput.ToString().Substring(0, strIteratorOutput.ToString().Length - 1));
            // *********
            StringBuilder fkImplementation = new StringBuilder(String.Empty);
            foreach (FieldStructure row in fields)
            {
                if ((row.ConstraintType == "F") && (!string.IsNullOrEmpty(row.RefColumnNameField.Trim())))
                {
                    string strIteratorFK = new UtilityMethod().GetIteratorPatternForDependentField(codeBehindContent);
                    strIteratorFK = strIteratorFK.Replace("#dependentDtoType#", GetRefTableDBMLName(row.RefTableName) + "Information");
                    strIteratorFK = strIteratorFK.Replace("#dependentAllEntity#", "All" + row.RefTableName);
                    strIteratorFK = strIteratorFK.Replace("#dependentEntity#", row.Field);
                    strIteratorFK = strIteratorFK.Replace("#dependentNameField#", row.RefColumnNameField);
                    strIteratorFK = strIteratorFK.Replace("#dependentValueField#", row.RefColumnName);
                    fkImplementation = fkImplementation.Append(Environment.NewLine + strIteratorFK);
                }
            }

            codeBehindContent = codeBehindContent.Replace("$[" + new UtilityMethod().GetIteratorPatternForDependentField(codeBehindContent) + "]$", fkImplementation.ToString());

            File.WriteAllText(CodeAttribute.ProjectLoc + "\\" + tableName + ".aspx.cs", codeBehindContent);
        }

        private void CreateUI(List<FieldStructure> fields, string tableName, string pageTitle)
        {
            string templateText = string.Empty;
            StreamReader streamReader = new StreamReader(@"ui.txt");
            templateText = streamReader.ReadToEnd();
            streamReader.Close();
            string primaryKey = fields.Where(a => a.ConstraintType == "P").Single().Field;
            string primaryKeyDataType =
                 TableAttributes.GetDataType(fields.Where(a => a.ConstraintType == "P").Single().DataType);
            templateText = templateText.Replace("#GridName#", "grd" + tableName);
            templateText = templateText.Replace("#codeFileName#", tableName + ".aspx.cs");
            templateText = templateText.Replace("#pageName#", tableName);
            templateText = templateText.Replace("#viewName#", tableName);
            templateText = templateText.Replace("#PageTitle#", pageTitle);
            templateText = templateText.Replace("#pkField#", primaryKey);
            StringBuilder strIteratorOutput = new StringBuilder(String.Empty);
            foreach (FieldStructure row in fields)
            {
                string strIterator = new UtilityMethod().GetIteratorPattern(templateText);
                strIterator = strIterator.Replace("#DBField#", row.Field);
                strIterator = strIterator.Replace("#ColHead#", new UtilityMethod().GetHeader(row.Field));
                strIteratorOutput.Append(Environment.NewLine + strIterator);
            }
            templateText = templateText.Replace("~[" + new UtilityMethod().GetIteratorPattern(templateText) + "]~", strIteratorOutput.ToString());

            strIteratorOutput = new StringBuilder(String.Empty);
            string inputControl = "";
            foreach (FieldStructure row in fields)
            {
                string strIterator = new UtilityMethod().GetIteratorPattern2(templateText);
                strIterator = strIterator.Replace("#ctrlID#", row.Field);
                if (row.ConstraintType != "F")
                    strIterator = strIterator.Replace("#labelText#", new UtilityMethod().GetHeader(row.Field));
                else
                    strIterator = strIterator.Replace("#labelText#", new UtilityMethod().GetHeader(row.RefTableName));
                if (row.ConstraintType != "F")
                {
                    if (row.ConstraintType == "P")
                        inputControl = @"<asp:Label ID=""lbl" + row.Field + @"Value"" runat=""server"" CssClass=""formLabel""></asp:Label> ";
                    else if (row.DataType.ToLower() == "bit")
                        inputControl = (@"<asp:CheckBox runat=""server"" ID=""chk" + row.Field + @""" />");
                    else if (row.DataType.ToLower() == "datetime")
                        inputControl = @"<uc1:CalendarScriptManager ID=""calanderScriptManager"" runat=""server"" /><crux:CalendarTextBox ID=""txt" + row.Field + @""" runat=""server"" UseCurrentDateAsStartDate=""true"" />";
                    else
                        inputControl = @"<crux:WaterMarkedTextBox ID=""txt" + row.Field + @""" WaterMarkText=""" + new UtilityMethod().GetHeader(row.Field) + @""" ValueRequired=""" + (row.NullAble ? "false" : "true") + @""" ErrorText=""" + new UtilityMethod().GetHeader(row.Field) + @" is required"" Width=""180""  MaxLength=""" + row.MaxLength + @""" runat=""server"" />";
                }
                else
                {
                    inputControl = @"<asp:DropDownList runat=""server"" " + @"ID=""ddl" + row.Field + @""" />";
                }

                strIterator = strIterator.Replace("#generalInputControl#", inputControl);
                strIteratorOutput.Append(Environment.NewLine + strIterator);
            }

            int removePos = templateText.IndexOf("~[[");
            int len = ("~[[" + new UtilityMethod().GetIteratorPattern2(templateText) + "]]~").Length;
            templateText = templateText.Remove(removePos, len);
            templateText = templateText.Insert(removePos, strIteratorOutput.ToString());
            File.WriteAllText(CodeAttribute.ProjectLoc + "\\" + tableName + ".aspx", templateText);
        }
    }
}
